package uk.ac.bbk.dcs.pakdd2014;

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;

public class CSVGenerator {
	private static void generate(String filename, Object[][] tuples){
		try {
			PrintWriter trainingSet = new PrintWriter("datasets/MC"+filename+".csv", "UTF-8");
			int size=tuples.length;
			for(int i=0; i<size-1;i++){
				for(int j=0; j<tuples[i].length-1;j++)trainingSet.print(tuples[i][j]+", ");
				trainingSet.print(tuples[i][tuples[i].length-1]);
				trainingSet.println();
			}
			
			if(tuples.length!=0){
				for(int j=0; j<tuples[size-1].length-1;j++)
					trainingSet.print(tuples[size-1][j]+", ");
				trainingSet.print(tuples[size-1][tuples[size-1].length-1]);
			}
			trainingSet.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	public static void generate(HashSet<MCLifeProbability> mclps){
		for(MCLifeProbability mclp:mclps){
			String[][] a=sort(mclp.getPobabilities());
			generate(mclp.getModule()+"_"+mclp.getComponent(),a);
		}
	}
	
	private static String[][] sort(String[][] arr){
		if (arr.length<=1){
			return arr;
		}
			
		String[][] ret=new String[arr.length][arr[0].length];
		String[][] first=sort(Arrays.copyOfRange(arr, 0, arr.length/2));
		String[][] second=sort(Arrays.copyOfRange(arr, arr.length/2,arr.length));
		int f=0;
		int s=0;
		for(int i=0;i<arr.length;i++){
			if(f>=first.length){
				ret[i]=second[s];
				s++;
			} 
			else if(s>=second.length){
				ret[i]=first[f];
				f++;
			} else{
				if(Integer.parseInt(first[f][0])<=Integer.parseInt(second[s][0])){
					ret[i]=first[f];
					f++;
				}
				else{
					ret[i]=second[s];
					s++;
				}
			}
		}
		return ret;
	}
}
